<?php
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

class table_er_filedset extends discuz_table
{
	public function __construct() {

		$this->_table ='er_filedset';
		$this->_pk    = 'id';

		parent::__construct();
	}

    /**
     * 获取文件列表
     * @param int $page 页码
     * @param int $pagesize 每页数量
     * @param array $query 查询条件
     * @return array 文件数组
     */
    public function fetch_query($page = 1, $pagesize = 10, $query) {
        $where = array();
        $params = array($this->_table);

        if(!empty($query) && is_array($query)) {
            foreach($query as $key => $value) {
                $allowed_keys = ['id', 'title','status', 'uid', 'url'];
                if(!in_array($key, $allowed_keys)) {
                    continue;
                }
                if($value!== null && $value!== '' && $value!= 0) {
                    if(is_int($value) || ctype_digit($value)) {
                        $where[] = $key.'=%d';	
                    } else {
                        $where[] = $key.'=%s';	
                    }	
                    $params[] = $value;
                }
            } 	
        }

        $count_sql = "SELECT COUNT(*) FROM %t";
		if(!empty($where)) {
			$count_sql .= " WHERE " . implode(' AND ', $where);
		}
		$total = DB::result_first($count_sql, $params);

		$sql = "SELECT * FROM %t";

		if(!empty($where)) {
			$sql .= " WHERE " . implode(' AND ', $where);
		}

        $sql .= " ORDER BY create_time DESC";

		$start = ($page - 1) * $pagesize;
        $limit_sql = " LIMIT $start, $pagesize";
		$sql.= $limit_sql;
		$data = DB::fetch_all($sql, $params);

		return array(
			'data' => $data,
			'total' => $total
		);
    }

    /**
     * 插入数据
     * @param array $data 要插入的数据
     */
    public function insert($data, $return_insert_id = false, $replace = false, $silent = false, $unbuffered = false) {
        $data['create_time'] = TIMESTAMP;
        $data['update_time'] = TIMESTAMP;
        return DB::insert($this->_table, $data);	
    }

    /**
     * 根据id获取文件信息
     * @param int $id 文件id
     * @return array 文件信息
    */
    public function fetch_by_id($id) {
        return DB::fetch_first("SELECT * FROM %t WHERE id=%d", array($this->_table, $id));
    }

    /**
     * 根据uid获取数量
     * @param int $uid 用户id
     */
    public function count_by_uid($uid) {
        return DB::result_first("SELECT COUNT(*) FROM %t WHERE uid=%d", array($this->_table, $uid));	
    }
}